<template>
  <div>
    <div class="box">
      <div class="button">
        <div class="button_left">
          <el-button type="primary" :icon="Plus" @click="addUp()"
            >添加</el-button
          >
        </div>
        <div class="button_reght">
          <el-button plain :icon="Grid" />
          <el-button plain :icon="Search" />
        </div>
      </div>
      <div class="science_list">
        <el-table
          :data="
            scenicList.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" fixed />
          <el-table-column label="轮播ID" width="100" fixed>
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.id }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="轮播名称" width="120" fixed>
            <template #default="scope">
              <!-- <el-popover effect="light" placement="top" width="auto"> -->
              <!-- <template #default>
                <div>name: {{ scope.row.name }}</div>
              </template> -->

              <div style="display: flex; align-items: center">
                <span>{{ scope.row.name }}</span>
              </div>

              <!-- </el-popover> -->
            </template>
          </el-table-column>
          <el-table-column label="轮播图片" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <img
                  :src="'https://c2c.kuxia.top' + scope.row.img"
                  alt=""
                  style="width: 50px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="120">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span>{{ scope.row.gname }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination
          :align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="scenicList.length"
        />
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="newlyIncreased"
      :title="status == -1 ? '新增' : '编辑'"
      :before-close="handleClose"
    >
      <el-scrollbar height="400px">
        <el-form :model="addition" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="轮播名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="addition.name"
              autocomplete="off"
              placeholder="请输入轮播名称"
              style="width: 90%"
            />
          </el-form-item>
          <el-form-item
            label="轮播图片"
            :label-width="formLabelWidth"
            style=""
            prop="img"
          >
            <el-input
              v-model="addition.img"
              placeholder="请上传图片"
              class="input-with-select"
              readonly="true"
              style="width: 90%"
            />
          </el-form-item>
          <div style="margin-left: 20%; padding-right: 8%">
            <el-upload
              ref="upload"
              v-model:file-list="fileList"
              class="upload-demo"
              action="https://scienicpc.kuxia.top/pcapi/File/fileimg"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleUpchange"
              :auto-upload="false"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button type="success" :icon="Upload">上传</el-button>
              <el-button type="primary" :icon="Operation" @click="submitUpload"
                >选择</el-button
              >
            </el-upload>
          </div>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="gid"
          >
            <el-select
              v-model="addition.gid"
              value-key="id"
              placeholder="请选择类型"
              style="width: 90%"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addScenic(ruleFormRef)">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
            v-if="status == -1"
          >
            新增
          </el-button>
          <el-button
            type="primary"
            @click="submitFormRedact(ruleFormRef)"
            v-else
          >
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { reactive } from "vue";
import { Plus, Search, Grid, Upload, Operation } from "@element-plus/icons-vue";
import {
  bannerIndex,
  imageUpload,
  bannerAdd,
  bannerDeletes,
  bannerEdits,
  goodsList
} from "@/api/banner";
import { genFileId, ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { bannerList } from "@/pinia/banner";
const user = bannerList();
console.log(user.bannerlist);
const currentPage = ref(1);
const pageSize = ref(5);
const scenicList = ref([]);
const newlyIncreased = ref(false);
const status = ref();
const options = ref([]);
const formLabelWidth = "140px";
const addition = reactive({
  name: "",
  img: "",
  gid: ""
});
const fileList = ref<UploadUserFile[]>([]);
const fileBanner = ref<UploadUserFile[]>([]);
const addUp = () => {
  status.value = -1;
  newlyIncreased.value = true;
  addition.name = "";
  addition.img = "";
  fileList.value.length = 0;
};
const upload = ref();
const handleExceed = files => {
  console.log(files);
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
const handleRemove = () => {
  console.log(123);
  console.log(addition.img);
  addition.img = "";
};

const submitUpload = () => {
  upload.value.submit();
};
const ruleFormRef = ref();
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "blur"
    }
  ],
  img: [
    {
      required: true,
      message: "请上传图片",
      trigger: "change"
    }
  ],
  gid: [
    {
      required: true,
      message: "请选择类型",
      trigger: "change"
    }
  ]
});
const loading = ref(true);
goodsList().then(res => {
  console.log(res);
  options.value = res.data.data;
});
const handleUpchange = uploadFile => {
  console.log(uploadFile);
  const param = new FormData(); //创建form对象
  param.append("file", uploadFile.raw, uploadFile.raw.name); //通过append向form对象添加数据
  console.log(param);
  imageUpload(param).then(res => {
    console.log(res);
    addition.img = "" + res.data.url;
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const submitForm = async formEl => {
  console.log(!formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(addition);
      //商品添加
      bannerAdd(addition).then(res => {
        console.log(res);
        newlyIncreased.value = false;
        bannerIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//商品编辑
const submitFormRedact = async formEl => {
  // newlyIncreased.value = false;
  console.log(!formEl);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(addition);
      bannerEdits({
        ...addition,
        id: status.value
      }).then(res => {
        console.log(res); // 成功回调
        newlyIncreased.value = false;
        bannerIndex().then(res => {
          scenicList.value = res.data.data;
        });
        if (res.data.code == 1) {
          ElMessage({
            message: res.data.msg,
            type: "success"
          });
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
function addScenic(formEl) {
  newlyIncreased.value = false;
  if (!formEl) return;
  formEl.resetFields();
}
//请求列表信息
if (user.bannerlist.length) {
  loading.value = false;
  scenicList.value = user.bannerlist;
} else {
  user.getList().then(res => {
    loading.value = false;
    console.log(res);
    scenicList.value = res;
  });
}
//每页条数改变时触发 选择一页显示多少行
function handleSizeChange(val) {
  console.log(`每页 ${val} 条`);
  currentPage.value = 1;
  pageSize.value = val;
}
//当前页改变时触发 跳转其他页
function handleCurrentChange(val) {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
}

function handleEdit(index, arr) {
  status.value = arr.id;
  bannerIndex({ id: arr.id }).then(res => {
    console.log(res);
    if (res.data.code == 0) {
      ElMessage.error(res.data.err);
    } else {
      fileList.value.length = 0;
      fileBanner.value.length = 0;
      newlyIncreased.value = true;
      addition.name = res.data.data[0].name;
      addition.img = res.data.data[0].img;
      addition.gid = res.data.data[0].tid;
      const str = {
        url: "https://c2c.kuxia.top" + res.data.data[0].img
      };
      fileList.value.push(str);
      console.log(addition);
    }
  });
}

function handleDelete(index, arr) {
  console.log(index);
  console.log(arr);
  bannerDeletes({ id: arr.id }).then(res => {
    console.log(res); // 成功回调
    bannerIndex().then(res => {
      scenicList.value = res.data.data;
    });
    if (res.data.code == 1) {
      ElMessage({
        message: res.data.msg,
        type: "success"
      });
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}
</script>

<style scoped>
.box {
  background-color: white;
  padding: 20px;
}
.button {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.paging {
  width: 100%;
  text-align: center;
}
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
